class Routesite < ActiveRecord::Base
	belongs_to :route
	belongs_to :site
	named_scope :defaultsiteroutes, :order => '"order" DESC', :conditions => {:site_id => '-1'}
	named_scope :dbsiteroutes, lambda { |site| {:order => '"order" DESC',:conditions => ['site_id = ?',site.id]}}

	def self.defaults
		#not sure why this had to be reversed
		dbsiteroutes = self.defaultsiteroutes.reverse
		dbroutes = Route.find(:all)
		routes = []
		for i in (0..dbroutes.length)
			if(dbsiteroutes.length == 0)
				dbroutes.each { |t| routes.push(t) }
				break
			end
			dbroutes.delete_if {|r|
				r.id == dbsiteroutes.first.route_id }
			routes.push(dbsiteroutes.shift.route)
		end
		routes
	end

	def self.siteRoutes(site)
		dbsiteroutes = self.dbsiteroutes(site)
		routes = self.defaults
		dbsiteroutes.each do |sr|
			#find in routes
			oldorder = routes.index(sr.route)
			routes[oldorder],routes[sr.order] =
				routes[sr.order],routes[oldorder]
		end
		routes.compact
	end
end
